using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PowerManage.API.Auth;
using PowerManage.Entity;
using PowerManage.Entity.Dtos.Permissions;
using PowerManage.Entity.Dtos.Roles;
using PowerManage.Service;

namespace PowerManage.API.Controllers;

/// <summary>
/// 角色管理
/// </summary>
[Route("api/[controller]")]
[PermissionAuthorize]
public class RoleController : BaseController
{
    private readonly IRoleService _roleService;
    private readonly IRolePermissionService _rolePermissionRepository;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserManager<EleUser> _userManager;
    private readonly RoleManager<EleRole> _roleManager;
    private readonly IMapper _mapper;

    public RoleController(IRoleService roleService, IRolePermissionService rolePermissionRepository,
        IHttpContextAccessor httpContextAccessor, UserManager<EleUser> userManager, RoleManager<EleRole> roleManager,
        IMapper mapper)
    {
        _roleService = roleService;
        _rolePermissionRepository = rolePermissionRepository;
        _httpContextAccessor = httpContextAccessor;
        _userManager = userManager;
        _roleManager = roleManager;
        _mapper = mapper;
    }

    /// <summary>
    /// 角色搜索
    /// </summary>
    /// <param name="rolePageReqDto"></param>
    /// <returns></returns>
    /// 默认返回200，使用Ok方法响应结果。
    [HttpGet]
    public async Task<IActionResult> Get([FromQuery] RolePageReqDto rolePageReqDto)
    {
        // 角色搜索
        RolePageRspDto rolePageRspDto = await _roleService.Query(rolePageReqDto);
        return Ok(rolePageRspDto);
    }

    /// <summary>
    /// 获取所有角色列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("all")]
    public async Task<IActionResult> GetAll()
    {
        // 获取所有角色列表
        List<RoleDto> roles = await _roleService.GetAll();
        return Ok(roles);
    }

    /// <summary>
    /// 获取角色的权限列表
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}/permissions")]
    public async Task<IActionResult> GetRolePermissions(long id)
    {
        // 获取角色的权限列表
        List<PermissionDto> rolePermissionDtos = await _rolePermissionRepository.GetRolePermissions(id);
        return Ok(rolePermissionDtos);
    }

    /// <summary>
    /// 更改角色的权限列表
    /// </summary>
    /// <param name="id"></param>
    /// <param name="rolePermissionDto"></param>
    /// <returns></returns>
    [HttpPut("{id}/permissions")]
    public async Task<IActionResult> UpdateRolePermissions(long id, [FromBody] RolePermissionDto rolePermissionDto)
    {
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var user = await _userManager.FindByNameAsync(userName);
        // 更新角色权限
        await _rolePermissionRepository.UpdateRolePermissions(id, rolePermissionDto.PermissionIds, user.Id);
        return Ok();
    }

    /// <summary>
    /// 添加角色
    /// </summary>
    /// <param name="roleCreateDto"></param>
    /// <returns></returns>
    /// 添加成功：返回201，使用Created方法响应结果，其中Created第一个参数为Url，我们这边默认为空。
    /// 添加失败：返回400，使用BadRequest方法响应结果。
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] RoleCreateDto roleCreateDto)
    {
        var role = _mapper.Map<EleRole>(roleCreateDto);
        //获取登录的用户
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var user = await _userManager.FindByNameAsync(userName);
        role.CreatorId = user.Id;
        // 添加角色
        var result = await _roleManager.CreateAsync(role);
        if (result.Succeeded)
        {
            return Created(string.Empty, role);
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("添加角色失败"));
        }
    }

    /// <summary>
    /// 更新角色
    /// </summary>
    /// <param name="id"></param>
    /// <param name="roleUpdateDto"></param>
    /// <returns></returns>
    /// 更新成功：返回204，使用NoContent方法响应结果，如果需要返回更新结果，使用Ok方法响应结果。
    /// 更新失败：返回400，使用BadRequest方法响应结果。
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(long id, [FromBody] RoleUpdateDto roleUpdateDto)
    {
        var role = await _roleManager.FindByIdAsync(id.ToString());
        if (role == null)
        {
            return BadRequest(new ResponseResultDto().SetNotFound());
        }

        _mapper.Map(roleUpdateDto, role);
        // 更新角色
        var result = await _roleManager.UpdateAsync(role);
        role.LastModificationTime = DateTime.Now;
        if (result.Succeeded)
        {
            return NoContent();
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("更新角色失败"));
        }
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    /// 更新成功：返回204，使用NoContent方法响应结果，如果需要返回更新结果，使用Ok方法响应结果。
    /// 更新失败：返回400，使用BadRequest方法响应结果。
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(long id)
    {
        var result = new ResponseResultDto();
        var role = await _roleManager.FindByIdAsync(id.ToString());
        if (id == 1)
        {
            return BadRequest(result.SetError("超级管理员不能删除"));
        }
        else if (role == null)
        {
            return BadRequest(result.SetNotFound());
        }

        // 删除角色
        await _roleManager.DeleteAsync(role);
        return NoContent();
    }
}